package com.jd.cmdb.tsc.zk.factory;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;


/**
 * Created by tianzhengguo on 2016/1/11.
 */
@Component
public class ClientFactoryBean extends AbstractFactoryBean<CuratorFramework> {
    public static final String NAMESPACE = null;

//    @Value("${zk.namespace}")
//    private String namespace;
    @Value("${zk.servers}")
    private String servers;
    @Value("${zk.sessionTimeout}")
    private int sessionTimeout;
    @Value("${zk.connectionTimeout}")
    private int connectionTimeout;
    @Value("${zk.retrySleepTime}")
    private int retrySleepTime;
    @Value("${zk.retryTimes}")
    private int retryTimes;

    @Override
    public Class<CuratorFramework> getObjectType() {
        return CuratorFramework.class;
    }

    @Override
    public CuratorFramework createInstance() throws Exception {
        CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
        CuratorFramework client = builder.connectString(servers)
                .sessionTimeoutMs(sessionTimeout)
                .connectionTimeoutMs(connectionTimeout)
                .canBeReadOnly(false)
                .retryPolicy(new ExponentialBackoffRetry(retrySleepTime, retryTimes))
//                .namespace(namespace)
                .namespace(NAMESPACE)
                .defaultData(null)
                .build();
        return client;
    }
}
